package com.ml.loan.common.model;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpStatus;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 通用返回对象封装
 *
 * @author Mickey
 * @date 2022/2/15 18:05
 */
public class JsonResult extends HashMap<String, Object> implements Serializable {

    private static final long serialVersionUID = 1L;

    public JsonResult() {
        put("success", Boolean.TRUE.booleanValue());
        put("code", HttpStatus.SC_OK);
        put("msg", "success");
    }

    public JsonResult setData(Object data) {
        put("data", data);
        return this;
    }

    public <T> T getData(Class<T> clazz) {
        return getData("data", clazz);
    }

    public <T> T getData(TypeReference<T> tTypeReference) {
        return getData("data", tTypeReference);
    }

    public <T> T getData(String key, Class<T> clazz) {
        Object data = get(key);
        String jsonString = JSON.toJSONString(data);
        T t = JSON.parseObject(jsonString, clazz);
        return t;
    }

    public <T> T getData(String key, TypeReference<T> tTypeReference) {
        Object data = get(key);
        String jsonString = JSON.toJSONString(data);
        T t = JSON.parseObject(jsonString, tTypeReference);
        return t;
    }

    public static JsonResult ok() {
        return ok("操作成功");
    }

    public static JsonResult ok(String msg) {
        return ok(HttpStatus.SC_OK, msg);
    }

    public static JsonResult ok(int code, String message) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.put("code", code);
        jsonResult.put("msg", message);
        jsonResult.put("success", HttpStatus.SC_OK == code ? Boolean.TRUE.booleanValue() : Boolean.FALSE.booleanValue());
        return jsonResult;
    }

    public static JsonResult ok(Object object) {
        return ok().setData(object);
    }

    /**
     * 返回失败
     */
    public static JsonResult error() {
        return error("操作失败");
    }

    /**
     * 返回失败
     */
    public static JsonResult error(String messag) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, messag);
    }

    /**
     * 返回失败
     */
    public static JsonResult error(int code, String message) {
        return ok(code, message);
    }

    @Override
    public JsonResult put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public boolean isSuccess() {
        return this.getSuccess().booleanValue();
    }

    private Boolean getSuccess() {
        return (Boolean) this.get("success");
    }


}
